/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.century.sjt.EMChat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.EMChat.adapter.NewFriendsMsgAdapter;
import com.century.sjt.EMChat.db.InviteMessgeDao;
import com.century.sjt.domain.InviteMessage;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.century.sjt.EMChat.domain.EaseUser;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 申请与通知
 *
 */
public class NewFriendsMsgActivity extends BaseActivity {
	private ListView listView;
	private List<InviteMessage> mDate=new ArrayList<>();
	private NewFriendsMsgAdapter adapter;
	InviteMessgeDao dao = new InviteMessgeDao(this);
	private Handler mHandler;
	private Context mContext;
	private SjtTitleBar titleBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_friends_msg);
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
					case 1:
						adapter.notifyDataSetChanged();
						TipUtil.closeProgressDialog();
						break;
					case 2:
						break;

				}
			}
		};



		List<InviteMessage> msgs = dao.getMessagesList();


		if (msgs.size()==0){
			mDate=msgs;
		}else {
			for (int i=0;i<msgs.size();i++){
				GetOneFriendData(msgs.get(i),i);
			}
		}

		initView();
		initEvent();

	}

	@Override
	protected void initView() {
		titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
		titleBar.setTitle(getResources().getString(R.string.tab_application_and_notify));
		titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		listView = (ListView) findViewById(R.id.list);

	}

	@Override
	protected void initEvent() {
		//设置adapter
		adapter = new NewFriendsMsgAdapter(this, 1, mDate,mQueue);
		listView.setAdapter(adapter);
		dao.saveUnreadMessageCount(0);
	}

	@Override
	protected void initData() {

	}


	/**
	 * 获取好友
	 */
	public void GetOneFriendData(final InviteMessage msg, final int i){

//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), NewFriendsMsgActivity.this);
		StringRequest stringRequest = new StringRequest(Request.Method.POST, com.century.sjt.util.Constant.GetOneFriendData, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				try {
//					TipUtil.closeProgressDialog();
					TipUtil.log("获取好友信息", response.toString(), 1);
					JSONTokener jsonParser = new JSONTokener(response);
					JSONObject res = (JSONObject) jsonParser.nextValue();
					String code = res.getString("code");
					String message = res.getString("message");
					JSONObject aData = res.getJSONObject("data");
					if (code.equals("200")) {//成功
						String userId  = aData.getString("userId");
						String nick = aData.getString("nickName");
						String initialLetter = aData.getString("nickInitialLetter");
						String mobile = aData.getString("mobile");
						String imageId = aData.getString("image");
						String imageUrl = aData.getString("imageUrl");
						EaseUser user =new EaseUser(userId);
						user.setNick(nick);
						user.setInitialLetter(initialLetter);
						user.setMobile(mobile);
						user.setAvatarid(imageId);
						user.setAvatar(imageUrl);
						msg.setNick(nick);
						msg.setAvatar(imageId);
						msg.setMobile(mobile);
						msg.setUser(user);
						mDate.add(msg);



					} else {//失败
                        TipUtil.showToast(message, NewFriendsMsgActivity.this, 1);
					}

					Message msg = new Message();
					msg.what = 1;
					mHandler.sendMessage(msg);
				} catch (Exception ex) {
					ex.printStackTrace();
					TipUtil.showToast(getResources().getString(R.string.error_service), NewFriendsMsgActivity.this, 1);

				}

			}

		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				TipUtil.showToast(getResources().getString(R.string.error_network), NewFriendsMsgActivity.this, 1);
				TipUtil.closeProgressDialog();
			}
		}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> map = new HashMap<String, String>();
				SharedPreferences mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
				String userId = mainSharedPreferences.getString("userId", "");
				map.put("loginId", userId);
				map.put("userId",msg.getFrom());

				return map;
			}
			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				SharedPreferences mainSharedPreferences =getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
				String cookie = mainSharedPreferences.getString("cookie", "");
				String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
				HashMap localHashMap = new HashMap();
				String cookieValue = cookie + ";" + rememberMeValue;
				localHashMap.put("Cookie", cookieValue);
				return localHashMap;
			}
		};

		mQueue.add(stringRequest);
	}
}
